#include "ThresholdEntropy.h"
#include <complex>



int ThresholdEntropy::calcThresholdValue (const vector< int > & histogram)
{
  double gMax = 0;
  int tMax = 0;
  double c0 = 0;
  
  double c1 = 0;
  for (int i = 0; i < histogram.size (); ++i)
	  c1 += histogram[i];

  for (int t = 0; t < 256; ++t)
  {
    double g = 0;
    if (c0 != 0)
    {
      for (int i = 0; i < t - 1; ++i)
      {
        if (histogram[i] != 0)
        {
          double p = (double)histogram[i] / c0;
          g -= p * log (p);
        }
      }
    }
    if (c1 != 0)
    {
      for (int i = t; i < 256; ++i)
      {
        if (histogram[i] != 0)
        {
          double p = (double)histogram[i] / c1;
          g -= p * log (p);
        }
      }
    }
    c0 += histogram[t];
    c1 -= histogram[t];
    if (t == 0)
    {
      gMax = g;
      tMax = 0;
    }
    else if (g > gMax)
    {
      gMax = g;
      tMax = t;
    }

  }
  return tMax;
}
